﻿//Copyright (c) Microsoft Corporation.  All rights reserved.

using Microsoft.ApplicationServer.Caching;
using System;

namespace Microsoft.Ted.Wacel.Cache
{
    public class WindowsAzureCachLockProvider: Base.ILockProvider
    {
        private DataCache mCache;        
        private string mRegion;
        public WindowsAzureCachLockProvider(DataCache cache, string region)
        {
            if (cache == null)
                throw new ArgumentNullException("DataCache can't be null.");
            mRegion = region;
            mCache = cache;
        }
        public void PutInSub(string key, long value)
        {
            if (!string.IsNullOrEmpty(mRegion))
                mCache.Put(key, value, mRegion);
            else
                mCache.Put(mRegion + "." + key, value, new DataCacheTag[] { new DataCacheTag(mRegion) });
        }
    
        public long Increment(string key, long increment, long defaultValue)
        {
            if (!string.IsNullOrEmpty(mRegion))
                return mCache.Increment(key, increment, defaultValue, mRegion);
            else
                return mCache.Increment(mRegion + "." + key, increment, defaultValue);
        }

        public long ReadAndLock(string key, long defaultValue, TimeSpan timespan, out object lockHandle)
        {
            DataCacheLockHandle cacheHandle;
            long ret = 0;
            if (!string.IsNullOrEmpty(mRegion))
                ret = mCache.ReadAndLock(key, defaultValue, timespan, out cacheHandle, mRegion);
            else
                ret = mCache.ReadAndLock(mRegion + "." + key, defaultValue, timespan, out cacheHandle, null);
            lockHandle = cacheHandle;
            return ret;
        }


        public void PutAndUnlock(string key, long value, object lockHandle)
        {
            if (!string.IsNullOrEmpty(mRegion))
                mCache.PutAndUnlock(key, value, (DataCacheLockHandle)lockHandle, mRegion);
            else
                mCache.PutAndUnlock(mRegion + "." + key, value, (DataCacheLockHandle)lockHandle);
        }

        public void Unlock(string key, object lockHandle)
        {
            if (!string.IsNullOrEmpty(mRegion))
                mCache.Unlock(key, (DataCacheLockHandle)lockHandle, mRegion);
            else 
                mCache.Unlock(key, (DataCacheLockHandle)lockHandle);

        }

        public void Clear()
        {
            if (!string.IsNullOrEmpty(mRegion))
                mCache.ClearRegion(mRegion);
            else
                throw new NotImplementedException();
        }
    }
}
